package com.wyzt.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.domain.ThumbImageConfig;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.wyzt.common.enums.ExceptionEnum;
import com.wyzt.common.exception.WyztException;
import com.wyzt.upload.config.UploadProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

@Service
@Slf4j
@EnableConfigurationProperties(UploadProperties.class)
public class UploadService {

    //注入fsdf
    @Autowired
    private FastFileStorageClient storageClient;//存储
    @Autowired
    private ThumbImageConfig thumbImageConfig;//缩略图生成

    @Autowired
    private UploadProperties properties;

    public String uploadImage(MultipartFile file) {
        try {
            // 1、图片信息校验
            // 1)校验文件类型
            String type = file.getContentType();
            if (!properties.getAllowTypes().contains(type)) {
                log.info("上传失败，文件类型不匹配：{}", type);
                throw new WyztException(ExceptionEnum.INVALID_FILE_ERROR);
            }
            // 2)校验图片内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null) {
                log.info("上传失败，文件内容不符合要求");
                throw new WyztException(ExceptionEnum.INVALID_FILE_ERROR);
            }
            // 2、保存图片---->fastDFS

            //文件后缀名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            //上传文件到fastDFS
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);

            // 2.3、拼接图片地址
            return properties.getBaseUrl() + storePath.getFullPath();
        } catch (Exception e) {
            //上传失败
            log.error("上传文件失败", e);
            throw new WyztException(ExceptionEnum.UPLOAD_FILE_ERROR);
        }
    }
}
